<template>
	<view class="player">
		<video id="video-player" ref="videoRef" style="width: 100%;" :title="title" :src="mediaSrc"
			:initial-time="initialTime" :controls="true" :muted="false" @loadedmetadata="handleLoadedMetadata"
			@pause="handlePause" @play="handlePlay" @canplay="handleCanPlay" @timeupdate="handleTimeUpdate"
			@ended="handleEnded" @error="videoErrorCallback" @seeking="handleSeeking" @seeked="handleSeeked">
		</video>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		getCurrentInstance,
		watch,
		nextTick
	} from 'vue'

	const props = defineProps({
		title: {
			type: String,
			default: ''
		},
		mediaSrc: {
			type: String,
			default: ''
		},
		initialTime: {
			type: Number,
			default: 0
		},
		number: {
			type: Number,
			default: 0
		}
	})

	const emits = defineEmits(['update:time', 'play', 'pause', 'ended', 'ready', 'seeking', 'seeked', 'status-change'])

	// 组件实例
	const instance = getCurrentInstance()

	// 视频状态
	const isVideoReady = ref(false)
	const currentTime = ref(0)
	const duration = ref(0)
	const isSeeking = ref(false)
	const playState = ref({
		canplay: false,
		seeking: false,
		stalled: false
	})

	// 视频上下文
	let videoContext = null
	let switchTimeout = null

	// 初始化视频上下文
	const initVideoContext = () => {
		return new Promise((resolve) => {
			const tryCreate = (attempt = 0) => {
				try {
					// 跨平台创建视频上下文
					if (process.env.UNI_PLATFORM === 'mp-weixin') {
						videoContext = wx.createVideoContext('video-player', instance.ctx || instance.proxy)
					} else {
						videoContext = uni.createVideoContext('video-player', instance.ctx || instance.proxy)
					}

					if (videoContext) {
						console.log("视频上下文创建成功")
						resolve(true)
					} else if (attempt < 3) {
						console.warn(`视频上下文创建失败，第${attempt + 1}次重试...`)
						setTimeout(() => tryCreate(attempt + 1), 500 * (attempt + 1))
					} else {
						console.error("视频上下文创建失败")
						resolve(false)
					}
				} catch (error) {
					console.error("创建视频上下文异常:", error)
					if (attempt < 3) {
						setTimeout(() => tryCreate(attempt + 1), 500 * (attempt + 1))
					} else {
						resolve(false)
					}
				}
			}

			tryCreate()
		})
	}

	// 重置视频状态
	const resetVideoState = () => {
		isVideoReady.value = false
		currentTime.value = 0
		duration.value = 0
		isSeeking.value = false
		playState.value = {
			canplay: false,
			seeking: false,
			stalled: false
		}
	}

	// 播放控制方法
	const play = async () => {
		// 确保视频已准备就绪
		if (!isVideoReady.value) {
			console.log("等待视频准备就绪")
			await new Promise(resolve => {
				const checkReady = setInterval(() => {
					if (isVideoReady.value) {
						clearInterval(checkReady)
						resolve()
					}
				}, 100)
			})
		}

		// 确保上下文存在
		if (!videoContext) {
			console.log("初始化视频上下文")
			await initVideoContext()
		}

		try {
			// 平台特定处理
			if (process.env.UNI_PLATFORM === 'mp-weixin') {
				// 微信小程序特殊处理
				videoContext.play()

				// 微信可能需要强制刷新
				setTimeout(() => {
					if (props.initialTime > 0) {
						videoContext.seek(props.initialTime + 0.1)
					}
				}, 300)
			} else if (process.env.UNI_PLATFORM === 'h5') {
				// H5平台处理
				const videoEl = document.getElementById('video-player')
				if (videoEl) {
					videoEl.muted = true
					await videoEl.play()
					videoEl.muted = false
				}
			} else {
				// 其他平台标准处理
				await videoContext.play()
			}
			emits('play')
		} catch (error) {
			console.error("播放失败:", error)
			// 终极回退方案
			setTimeout(() => {
				const videoEl = document.getElementById('video-player')
				if (videoEl && typeof videoEl.play === 'function') {
					console.log("尝试DOM元素直接播放")
					videoEl.play()
				}
			}, 500)
		}
	}

	const pause = () => {
		if (videoContext) {
			videoContext.pause()
			emits('pause')
		}
	}

	// 重新播放方法
	const replay = async () => {
		console.log("重新播放视频")
		if (videoContext) {
			// 先跳转到开始位置
			await seek(0)
			// 延迟播放
			setTimeout(async () => {
				await play()
			}, 100)
		}
	}

	// 视频事件处理
	const handleLoadedMetadata = (e) => {
		console.log("视频元数据加载完成")
		isVideoReady.value = true
		emits('ready')

		// 设置初始时间
		if (props.initialTime > 0) {
			setTimeout(() => {
				if (videoContext) {
					videoContext.seek(props.initialTime)
					console.log(`已设置初始时间: ${props.initialTime}秒`)
				}
			}, 300)
		}
	}

	const seek = (s) => {
		if (videoContext && !isSeeking.value) {
			isSeeking.value = true
			playState.value.seeking = true
			emits('seeking', s)
			videoContext.seek(s)
		}
	}

	const handleCanPlay = () => {
		playState.value.canplay = true
		isVideoReady.value = true
	}

	const handleSeeking = () => {
		isSeeking.value = true
		playState.value.seeking = true
		emits('seeking', currentTime.value)
	}

	const handleSeeked = () => {
		isSeeking.value = false
		playState.value.seeking = false
		emits('seeked', currentTime.value)
	}

	// 处理视频控件播放事件
	const handlePlay = (e) => {
		console.log("视频控件播放事件触发")
		emits('play')
		// 通知父组件状态变化
		emits('status-change', 'play')
	}

	// 处理视频控件暂停事件
	const handlePause = (e) => {
		console.log("视频控件暂停事件触发")
		emits('pause')
		// 通知父组件状态变化
		emits('status-change', 'paus')
	}

	//播放时间s
	const handleTimeUpdate = (e) => {

		currentTime.value = e.detail.currentTime;
		duration.value = e.detail.duration
		emits('update:time', {
			currentTime: Math.floor(currentTime.value),
			duration: duration.value,
			progress: duration.value > 0 ? (currentTime.value / duration.value) * 100 : 0
		})

	}

	const handleEnded = () => {
		console.log("视频播放结束")
		emits('ended')
		// 通知父组件状态变化
		emits('status-change', 'end')
	}

	const videoErrorCallback = (err) => {
		console.error("视频播放错误:", err.detail.errMsg || err)
	}

	// 微信专用修复
	const weixinFix = () => {
		if (process.env.UNI_PLATFORM !== 'mp-weixin') return

		// 微信可能需要强制刷新视频元素
		const forceRefresh = () => {
			const temp = props.mediaSrc
			// 这里不能直接修改props，需要父组件配合
			console.log("建议父组件在加载失败时刷新视频源")
		}
		// 首次加载后检查
		onMounted(() => {
			setTimeout(() => {
				if (!isVideoReady.value) {
					forceRefresh()
				}
			}, 2000)
		})
	}

	// 监听mediaSrc变化
	watch(() => props.mediaSrc, (newSrc, oldSrc) => {
		if (newSrc !== oldSrc) {
			console.log('视频源变化:', oldSrc, '->', newSrc)

			// 清除之前的切换操作
			if (switchTimeout) {
				clearTimeout(switchTimeout)
			}

			// 重置状态
			resetVideoState()

			// 延迟初始化确保DOM更新
			switchTimeout = setTimeout(async () => {
				await initVideoContext()
			}, 200)
		}
	})

	// 监听number变化
	watch(() => props.number, (newNumber, oldNumber) => {
		if (newNumber !== oldNumber) {
			console.log('视频编号变化:', oldNumber, '->', newNumber)
			// 重置状态，避免状态污染
			resetVideoState()
		}
	})

	// 初始化
	onMounted(() => {
		initVideoContext()
		weixinFix()
	})

	// 暴露方法
	defineExpose({
		play,
		pause,
		seek,
		replay,
		isReady: () => isVideoReady.value,
		getCurrentTime: () => currentTime.value,
		getDuration: () => duration.value,
		isSeeking: () => isSeeking.value
	})
</script>

<style lang="scss">
</style>